<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>


    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告标题 -->
      <el-alert title="注意:只允许第三级分类设置相关参数!!" type="warning" :closable="false" show-icon> </el-alert>

      <!-- 商品分类 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
              v-model="selectedCateKeys"
              :options="cateList"
              :props="cateProps"
              @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>


      <!-- tabs 分页区域 -->
       <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBan" @click="addUserDialogVisible = true">
              动态参数
            </el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTableData" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 标签 -->
                  <el-tag v-for="(item , index ) in scope.row.attr_vals" :key="index" closable @close="handleClosed(index , scope.row)">
                    {{item}}
                  </el-tag>
                  <!-- 文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
               
                </template>
              </el-table-column>

              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数属性" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserDialogVisible(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeShop(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>


          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBan" @click="addUserDialogVisible = true">
              静态属性
            </el-button>
            <!-- 静态参数表格 -->
            <el-table :data="onlyTableData" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 标签 -->
                  <el-tag v-for="(item , index ) in scope.row.attr_vals" :key="index" closable @close="handleClosed(index , scope.row)">
                    {{item}}
                  </el-tag>
                  <!-- 文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                               
                </template>
              </el-table-column>

              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数属性" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserDialogVisible(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeShop(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>


        </el-tabs>



    </el-card>

    <!-- 动态参数、静态属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText "
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addUserDialogClosed"
      >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText "
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editUserDialogClosed"
      >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
  export default{
    data(){
      return{
        //商品分类数据列表
        cateList:[],
        //级联选择器的双向绑定数组
        selectedCateKeys:[],
        //级联选择器的配置对象
        cateProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children',
          expandTrigger: 'hover'
        },
        //双向绑定数据
        activeName:'many',
        //动态参数
        manyTableData:[],
        //静态属性
        onlyTableData:[],
        //控制动态参数、静态属性的对话框的显示与隐藏
        addUserDialogVisible:false,
        //对话框的表单数据对象
        addForm:{
          attr_name:''
        },
        //对话框的表单验证规则
        addFormRules:{
          attr_name:[
            { required: true, message: '请输入', trigger: 'blur' },
          ]
        },
        //控制修改对话框的显示与隐藏
        editDialogVisible:false,
        //修改对话框的表单数据对象
        editForm:{},
        //对话框的表单验证规则
        editFormRules:{
          attr_name:[
            { required: true, message: '请输入', trigger: 'blur' },
          ]
        }
      }
    },
    created(){
      this.getCateList()
    },
    methods:{
      async getCateList(){
        const {data: res}  = await this.$http.get("categories")
        if(res.meta.status !== 200) return this.$message.error(res.meta.mssg)

        this.cateList = res.data
      },
      //级联选择器 改变一次触发一次
      async handleChange(){
        this.getParamsData()
      },
      //tab 页签点击事件的处理函数
      handleTabClick(){
        this.getParamsData()
      },
      //级联三级和点击切换都要获取数据
      async getParamsData(){
        //控制级联选择器的范围
        //如果不是3，清空
        if(this.selectedCateKeys.length !== 3){
          this.selectedCateKeys = []
          this.manyTableData = []
          this.onlyTableData = []
          return
        }
        //是三级分类
        // console.log(this.selectedCateKeys)
        const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
        //判断之前要对数据进行处理
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        // console.log(res.data)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        //判断是动态还是静态
        if(this.activeName === 'many'){
          this.manyTableData = res.data
        }else{
          this.onlyTableData = res.data
        }

      },
      //添加对话框的关闭事件
      addUserDialogClosed(){
        this.$refs.addFormRef.resetFields()
      },
      //请求添加动态参数或者静态属性
      addParams(){
        this.$refs.addFormRef.validate(async valid => {
          //预验证
          if(!valid) return;
          //验证通过
          const {data : res } = await this.$http.post(`categories/${this.cateId}/attributes`,{
            attr_name:this.addForm.attr_name,
            attr_sel:this.activeName
          })

          // console.log(res)
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)


          this.addUserDialogVisible = false
          this.getParamsData()
          this.$message.success(res.meta.msg)
        })
      },
      //根据ID拿值
      async editUserDialogVisible(attr_id){
        const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{params:{attr_sel:this.activeName}})

        // console.log(res)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editForm = res.data
        this.editDialogVisible = true
      },
      //监听关闭事件，清空对话框
      editUserDialogClosed(){
        this.$refs.editFormRef.resetFields()
      },
      //点击 修改信息
      editParams(){
        this.$refs.editFormRef.validate(async valid => {
          if(!valid) return

          const {data : res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
            attr_name:this.editForm.attr_name,
            attr_sel:this.activeName
            })

          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

          this.getParamsData()
          this.editDialogVisible = false
          this.$message.success(res.meta.msg)

        })
      },
      //点击 删除商品
      async removeShop(attr_id){
        const confirmRes = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).catch(err => err)

        if(confirmRes !== 'confirm') return this.$message.error('已经取消了删除')

        const {data : res }  = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success(res.meta.msg)
      },
      //失去焦点或者按下键盘的回车所触发的事件
      async handleInputConfirm(scope){
        //输入的内容不合法
        if(scope.inputValue.trim().length === 0){
          scope.inputValue = ''
          scope.inputVisible = false
          return
        }
        //合法，操作后面
        //循环
        scope.attr_vals.push(scope.inputValue)
        //重置
        scope.inputValue = ''
        scope.inputVisible = false

        //上面只是存在前端页面，数据要持久化必须保持在数据库中
        this.saveDataBase(scope)
      },
      //按钮的显示
      showInput(scope){
        scope.inputVisible = true
        //文本框自动获取焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      //监听tag标签的关闭事件
      handleClosed(index,scope){
        scope.attr_vals.splice(index,1)
        this.saveDataBase(scope)

      },
      // 抽离请求方法
      async saveDataBase(scope){
        const { data : res } = await this.$http.put(`categories/${this.cateId}/attributes/${scope.attr_id}`,{
          attr_name:scope.attr_name,
          attr_sel:scope.attr_sel,
          attr_vals:scope.attr_vals.join(' ')
        })

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
      }


    },
    computed:{
      //如果按钮需要被禁用，返回true 否则返回false
      isBan(){
        if(this.selectedCateKeys.length !== 3){
          return true
        }
        return false
      },
      //选中第三级ID
      cateId(){
        if(this.selectedCateKeys.length === 3){
          return this.selectedCateKeys[2]
        }
        return  null
      },
      //显示动态参数还是静态属性
      titleText(){
        if(this.activeName === 'many'){
          return '动态属性'
        }
        return '静态参数'
      }


    }

  }
</script>

<style lang="less" scoped>

.el-alert{
  margin-bottom: 20px;
}



.el-tag{
  margin: 0px 10px;
}

.input-new-tag{
  width: 120px;
}


</style>
